package com.dayu.finecomm.utils;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * AES-128-ECB加解密
 * 
 * @author Chenjiawei
 *
 *         2017年6月19日
 */
public class Encrypt {

	public static boolean initialized = false;

	public static final String ALGORITHM = "AES/ECB/PKCS7Padding";

	/**
	 * 加密
	 * 
	 * @param bs
	 *            要被加密的字节
	 * @param key
	 *            密钥
	 * @return
	 */
	public static byte[] Aes256Encode(byte[] bs, byte[] key) {
		initialize();
		byte[] result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // 生成加密解密需要的Key
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			result = cipher.doFinal(bs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 解密
	 * 
	 * @param bytes
	 *            要被解密的字节数组
	 * @param key
	 *            密钥
	 * @return
	 */
	public static byte[] Aes256Decode(byte[] bytes, byte[] key) {
		initialize();
		byte[] decoded = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // 生成加密解密需要的Key
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			decoded = cipher.doFinal(bytes);
		} catch (Exception e) {
			decoded = null;
			e.printStackTrace();
		}
		return decoded;
	}

	public static void initialize() {
		if (initialized)
			return;
		Security.addProvider(new BouncyCastleProvider());
		initialized = true;
	}

}
